﻿using Lrd.Permissions.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Lrd.Permissions.Demo.Web.Controllers
{
    /// <summary>
    /// 测试
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
   
    public class TestController : ControllerBase
    {

        private readonly UserManager<User> _userManager;
        private readonly SignInManager<User> _signInManager;

        private readonly IUnitOfWork _unitOfWork;
        public TestController(UserManager<User> userManager, SignInManager<User> signInManager, IUnitOfWork unitOfWork)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _unitOfWork = unitOfWork;
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IdentityResult> AddUser()
        {

            _unitOfWork.BeginOrUseTransaction();
             var users= await _userManager.Users.ToListAsync();
            var count = users.Count;
            User user = new User();
            user.UserName = $"Admin{count}";
            user.NormalizedUserName = "管理员{count}";
            user.EmailConfirmed = false;
            user.PhoneNumberConfirmed = false;
            user.TwoFactorEnabled = false;
            user.LockoutEnabled = false;
            user.AccessFailedCount = 0;
            user.IsSystem = false;
            user.IsLocked = false;
            var result=  await _userManager.CreateAsync(user,"123456");
            _unitOfWork.Commit();
            return result;
        }

        [HttpPost]
        //[Authorize]
        public async Task<IEnumerable<User>> GetUserAsync()
        {
            //var userList = await _userManager.Users.ToListAsync();
            var userList=  _unitOfWork.FromSql<User>(@"SELECT * FROM  User");
            await Task.CompletedTask;
            return userList;
        }

        [AllowAnonymous]

        [HttpPost]
        public async Task<JsonResult> Jwtoken(LoginDto dto)
        {
            //var result = await _signInManager.PasswordSignInAsync(dto.UserName, dto.Password, false, lockoutOnFailure: false);
            var user = await _userManager.FindByNameAsync(dto.UserName);
            var result = await _signInManager.CheckPasswordSignInAsync(user, dto.Password, lockoutOnFailure: false);
            var jwtToken = CreateJwtToken(user);
            //await _signInManager.SignInAsync(user,false);
            
            return new JsonResult(new { Succeeded = result.Succeeded,Msg=result.Succeeded?"登录成功":"登录失败",Token=$"Bearer {jwtToken}" });

        }

        private string CreateJwtToken(User user)
        {
          
            Claim[] claims =
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.UserName)
            };
            var token = CreateToken(claims);
            return token;
        }

        private static string CreateToken(Claim[] claims)
        {
            SecurityKey key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("8619F7C3-B53C-4B85-99F0-983D351ECD82"));
            SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
            DateTime now = DateTime.Now;
            double days = Math.Abs(1) > 0 ? Math.Abs(1) : 7;
            DateTime expires = now.AddMinutes(days);

            SecurityTokenDescriptor descriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Audience = "lrd identity",
                Issuer = "lrd identity",
                SigningCredentials = credentials,
                NotBefore = now,
                IssuedAt = now,
                Expires = expires
            };
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            SecurityToken token = tokenHandler.CreateToken(descriptor);
            return tokenHandler.WriteToken(token);
        }
    }

    public class LoginDto
    {

        public string UserName { get; set; }

        public string Password { get; set; }


    }
}
